#! /usr/bin/env python
# encoding: utf-8

from waflib import Utils

# the following two variables are used by the target "waf dist"
VERSION = '0.9.0'
APPNAME = 'wxDCDesigner'

# Compiler (compiler_cxx, g++)
MY_C_COMPILER = 'gcc'
MY_CPP_COMPILER = 'g++'

# these variables are mandatory ('/' are converted automatically)
top = '.'
out = 'build'

def options(opt):
  opt.load(MY_C_COMPILER)
  opt.load(MY_CPP_COMPILER)
  opt.load('winres')

def configure(conf):

  conf.find_program(['wxformbuilder', 'wxFormBuilder'], var='WX_FORM_BUILDER')
  conf.find_program('strip', mandatory=False)
  
  conf.load(MY_C_COMPILER)
  conf.load(MY_CPP_COMPILER)

  if Utils.unversioned_sys_platform() == 'win32':
    conf.load('winres')
    conf.check_env_variable('WXWIN')
    conf.check_env_variable('WXCFG')

def build(bld):
  if Utils.unversioned_sys_platform() == 'win32':
    bld.program(source = 'other/wx_config/wx-config-win.cpp', target = 'wx-config')
    bld.add_group()

  # Delayed wxWidgets library flag detection and configuration
  def delayed_check_cfg(self):
    import waflib.Context
    utility_path = self.generator.bld.find_program('wx-config', path_list=['build'])
    ret = self.generator.bld.cmd_and_log([ utility_path, '--cxxflags', '--libs' ], output=waflib.Context.STDOUT, quiet = waflib.Context.BOTH)
    self.generator.bld.parse_flags(ret, 'WX')

  bld(rule = delayed_check_cfg, always = True)

  bld.add_group()

  # Other task create only after configuration
  import waflib.Build 
  bld.post_mode = waflib.Build.POST_LAZY

  # Build main program
  bld.recurse('dialogs utility utility/lua_wrappers other/lua other/sheet other/xml_config distr')
  bld.program(source = ' \
    common/communicator_options.cpp \
    common/design.cpp \
    common/export_module.cpp \
    common/find_file_module.cpp \
    common/language_const.cpp \
    common/size_storage_helper.cpp \
    base_level_exchange_module.cpp \
    base_writer.cpp \
    cell_data_item.cpp \
    component_info_const.cpp \
    component_info_panel.cpp \
    component_item.cpp \
    component_tree_panel.cpp \
    component_type_description.cpp \
    current_configuration.cpp \
    custom_events.cpp \
    dcdesigner_app.cpp \
    dcdesigner_main.cpp \
    design_converter.cpp \
    design_panel.cpp \
    file_exchange_module.cpp \
    gui_frames.cpp \
    import_item.cpp \
    info_panel.cpp \
    misc_func.cpp \
    race_item.cpp \
    stored_values.cpp \
    tab_panel.cpp \
    unit_calculator.cpp \
    unit_field_description.cpp \
    converters/design.cpp \
    parsers/base_parser.cpp \
    parsers/component_parser.cpp \
    parsers/exchanger.cpp \
    parsers/import_parser.cpp \
    parsers/race_parser.cpp \
    parsers/unit_part_parser.cpp \
    resource.rc \
  '
    , target = 'wxDCDesigner/wxDCDesigner'
    , includes = [ '.', 'other/sheet/include', 'wxFormBuilder' ]
    , use = [ 'WX', 'dialog_static_lib', 'lua', 'sheet_static_lib', 'wx_xml_config_static_lib', 'utility_static_lib', 'lua_utility_static_lib' ]
    , features='strip')


from waflib.Configure import conf
from waflib import Task, TaskGen
from waflib.TaskGen import extension

# Convert from fbp -> .h/.cpp
def fbp_to_cpp(task):
  import shutil
  src = task.inputs[0].abspath()
  tgt = task.outputs[0].abspath()
  # Create files in source dir
  ret = task.exec_command([ task.env['WX_FORM_BUILDER'], '-g', src ])
  if (ret):
    return ret
  # Move .h and .cpp to build dir
  shutil.move(task.outputs[0].get_src().abspath(), task.outputs[0].abspath())
  shutil.move(task.outputs[1].get_src().abspath(), task.outputs[1].abspath())
  return 0

Task.task_factory('fbp_converter', func = fbp_to_cpp, color = 'BLUE', ext_out = [ '.h' ])

@extension('.fbp')
def process_fbp(self, node):
  cpp_node = node.change_ext('.cpp')
  hpp_node = node.change_ext('.h')
  self.create_task('fbp_converter', node, [cpp_node, hpp_node])
  self.source.append(cpp_node)

# Copy file from source to destination folder
def python_copy(task):
  import shutil
  src = task.inputs[0].abspath()
  dst = task.outputs[0].abspath()
  shutil.copyfile(src, dst)
  return 0

@conf
def copy_files(self, files, target_dir, source_dir = '.'):
  for x in files.split():
    self(rule = python_copy, source = source_dir + '/' + x, target = target_dir + '/' + source_dir + '/' + x, color = 'CYAN')
  return 0

# Remove additional info from executable
class strip_executable(Task.Task):
  run_str = '${STRIP} ${SRC}'
  color   = 'BLUE'

@TaskGen.feature('strip')
@TaskGen.after('apply_link')
def add_strip_task(self):
  try:
    link_task = self.link_task
  except:
    return
  if (len(self.env['STRIP'])):
    tsk = self.create_task('strip_executable', self.link_task.outputs[0])

@conf
def check_env_variable(self, var_name):
  import os
  ret = var_name in os.environ
  self.msg('Checking for environment variable ' + var_name, ret or False)

  if not ret:
    self.fatal('Could not find environment variable %s' % var_name)
  return ret
